package com.countertack.forensics;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.ResultSet;

import com.countertack.impala.ImpalaConnector;
import com.countertack.ssh.SSHManager;
import com.countertack.utils.HttpClientUtils;
import com.countertack.vmware.VMWareConnector;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.vmware.vim25.mo.VirtualMachine;

public class ForensicTest {

	public static void main2(String[] args) throws Exception {

		// connect to hadoop impala
	
		ImpalaConnector iConnector;

		iConnector = ImpalaConnector
				.createImpalaConnectorInstance("10.150.100.243");

		// connect to esxi and starting virtual machines

		VMWareConnector esxiConnector = new VMWareConnector("10.140.63.49");
//poweredOn
	final	VirtualMachine endPointMachine = esxiConnector
				.getVirtualMachineByname("win7x64-sym-1");
System.out.println("power state >>>"+endPointMachine.getRuntime().powerState);
	
		String endpointMachineStatus = esxiConnector
				.getVirtualMachineStatus(endPointMachine);

		if (endpointMachineStatus == null) {

			System.out.println("Power on  endpoint machine .....");

			esxiConnector.startVirtualMachine(endPointMachine);

			Thread.sleep(600000);

		} else {

			if ("notRunning".equalsIgnoreCase(endpointMachineStatus)) {

				esxiConnector.reStartVirtualMachine(endPointMachine);

				System.out.println("Rebooting endpoint machine .....");

				Thread.sleep(600000);

			}

		}



		// initialising ssh to virtual machines
		
		System.out.println("ipdsdsmmfd>>>"+endPointMachine.getGuest().ipAddress);
	

		final SSHManager endpointSsh = new SSHManager("user", "password1",
				endPointMachine.getGuest().ipAddress);
		endpointSsh.connect();

	
		// install agent

	endpointSsh
				.copyFile(
					"C:\\Users\\user\\Desktop\\ctagent\\CounterTack Agent Installer Hiding.exe",
						"CounterTack Agent Installer Hiding.exe");

	endpointSsh
				.runCommand("cmd /c \"C:\\Users\\user\\CounterTack Agent Installer Hiding.exe\" /S /HOST:10.150.100.243 /PORT:443");

		System.out.println("Installing agent on endpoint");
		Thread.sleep(120000);
		
		String eId = null;
		ResultSet endpointIdRes = iConnector
				.executeQueryAndReturnResults("select id from endpoints where ip='"
						+ endPointMachine.getGuest().ipAddress
						+ "'"
						+ " and status='ON' and ip is not null order by time_started asc limit 1");
		
		
		
		

		while (endpointIdRes.next()) {
			try{
				eId = endpointIdRes.getString(1);
			}catch(Exception e){
				
				
			}
			

			System.out.println("endpoint Id>>>>>>" + eId);

		}

		if (eId == null) {

			System.out.println("endpoint is not installed");

			System.exit(0);

		}
	
		pauseEndpoint(eId);
		Thread.sleep(60000);
		endpointSsh.closeSession();
		endpointSsh.doReconnect=false;
		// retriving endpoint id

	

		// applying profile to endpoint

		String payload = "{ " + "  \"type\": \"apply_profile_to_endpoints\", "
				+ "  \"profile\":\"Ramana-Profile-AnyInbound\", "
				+ "  \"endpoints\":[ " + "\"" + eId + "\" " + "] " + "} ";
		System.out.println("payload>>>" + payload);
		//
		

		// pause and resume endpoint

	//pauseEndpoint(eId);
//		Thread.sleep(30000);
//
//		resumeEndpoint(eId);
//		Thread.sleep(30000);

		
		//Thread.sleep(3000);

		// start netcat server in endpoint machne

		
	new Thread(new Runnable() {
			
			@Override
			public void run() {
				endpointSsh
				.runCommand("cmd /c cd C:\\Users\\user\\Desktop\\nc111nt && nc.exe -v -w 30 -l -p 31337 && exit");// TODO Auto-generated method stub
				
			}
		}).start();
	Thread.sleep(3000);
	
	
	HttpClientUtils.composePostRequest(
			"https://10.150.100.243:9090/api/v1/endpoints/command", payload);
	
	Thread.sleep(3000);
		// resume endpoint

		resumeEndpoint(eId);
		
		
		Thread.sleep(30000);
		

//		// start netcat client in client machine
//new Thread(new Runnable() {
//	
//	@Override
//	public void run() {
//		
//		31337Command("cmd /c cd C:\\Users\\user\\Desktop\\nc111nt && nc.exe "
//				+ endPointMachine.getGuest().ipAddress + " 31337 helloworld");// TODO Auto-generated method stub
//		
//	}
//}).start();

//Thread.sleep(3000);
	
		
		
		
		
		Thread.sleep(60000);

		// retriving behavior id

		ResultSet brs = iConnector
				.executeQueryAndReturnResults("select hex(id) from behaviors where uri like '%"
						+ eId + "%'  order by event_start_time desc limit 1");
		String bhid = null;

		while (brs.next()) {
			bhid = brs.getString(1);

		}
		System.out.println("behavior id>>>>" + bhid);

		// verifying netcat client
		ResultSet netcatpros = iConnector
				.executeQueryAndReturnResults("select target_thread_process_name from behaviors_denorm where hex(behavior_id)='"
						+ bhid + "' and behavior_id is not null and is_origin=1");

		while (netcatpros.next()) {
			String path = netcatpros.getString(1);

			if (path != null) {

				System.out.println("path>>>" + path);
				if (path.contains("nc")) {

					System.out.println("testcase passed");
					
					System.exit(0);
					return;

				}

			}
		}
		System.out.println("testcase failed");
		System.exit(0);
		
		

	}

	public static void pauseEndpoint(String eid) throws Exception{

		String pause = "{ " + "  \"type\":\"pause_many\", "
				+ "  \"endpoints\":[ " + "\"" + eid + "\" " + " ] " + "} ";

		HttpClientUtils.composePostRequest(
				"https://10.150.100.243:9090/api/v1/endpoints/command", pause);

	}

	public static void resumeEndpoint(String eid) throws Exception{

		String resume = "{ " + "  \"type\":\"resume_many\", "
				+ "  \"endpoints\":[ " + "    \"" + eid + "\" " + "] " + "} ";

		HttpClientUtils.composePostRequest(
				"https://10.150.100.243:9090/api/v1/endpoints/command", resume);

	}
	
	public static void main34545(String[] args) throws Exception {

		char ctrlC = 0x3;
		String controlC = Character.toString(ctrlC);
		String command[] = { "C:/Users/user/Desktop/nc111nt/nc.exe",
				"10.140.63.156 31337 < C:\\Users\\user\\Desktop\\hello.txt",
				controlC };

		StringBuffer output = new StringBuffer();
		try {
			Process p = Runtime.getRuntime().exec(command);

			InputStreamReader ir = new InputStreamReader(p.getInputStream());
			int outputChar = 0;
			while ((outputChar = ir.read()) != -1) {
				output.append((char) outputChar);
				if (!ir.ready()) { // If the next read is not

					// guaranteed, come out of loop.
					break;
				}
			}

			System.out.println("netcat is connected");

			// String controlC = "\u0003";

			ir.close();
			p.destroy();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("netcat output >>>>>" + output.toString());

	}
	public static void main4(String[] args){
		
String s=null;
		try {

	        // run the Windows command (dir)
	            // using the Runtime exec method:
	            Process p = Runtime.getRuntime().exec("cmd /c ftp 10.140.63.154");

	            BufferedReader stdInput = new BufferedReader(new 
	                 InputStreamReader(p.getInputStream()));

	            BufferedReader stdError = new BufferedReader(new 
	                 InputStreamReader(p.getErrorStream()));

	            // read the output from the command
	            System.out.println("Here is the standard output of the command:\n");
	            while ((s = stdInput.readLine()) != null) {
	                System.out.println(s);
	            }

	            // read any errors from the attempted command
	            System.out.println("Here is the standard error of the command (if any):\n");
	            while ((s = stdError.readLine()) != null) {
	                System.out.println(s);
	            }

	            System.exit(0);
	        }
	        catch (IOException e) {
	            System.out.println("exception happened- here's what I know: ");
	            e.printStackTrace();
	            System.exit(-1);
	        }
	    }
		
		
		
		
		
		
	
	
	
	
	
	public static void main(String[] args) throws Exception{
		
		ImpalaConnector iConnector;

		iConnector = ImpalaConnector
				.createImpalaConnectorInstance("10.150.100.243");

		// connect to esxi and starting virtual machines

		VMWareConnector esxiConnector = new VMWareConnector("10.140.63.49");
//poweredOn
	final	VirtualMachine endPointMachine = esxiConnector
				.getVirtualMachineByname("win7x64-sym-2");
System.out.println("power state >>>"+endPointMachine.getRuntime().powerState);
		
		String endpointMachineStatus = esxiConnector
				.getVirtualMachineStatus(endPointMachine);

		if (endpointMachineStatus == null) {

			System.out.println("Power on  endpoint machine .....");

			esxiConnector.startVirtualMachine(endPointMachine);

			Thread.sleep(600000);

		} else {

			if ("notRunning".equalsIgnoreCase(endpointMachineStatus)) {

				esxiConnector.reStartVirtualMachine(endPointMachine);

				System.out.println("Rebooting endpoint machine .....");

				Thread.sleep(600000);

			}

		}

	

		// initialising ssh to virtual machines
		
		System.out.println("ipdsdsmmfd>>>"+endPointMachine.getGuest().ipAddress);
	

		final SSHManager endpointSsh = new SSHManager("user", "password1",
				endPointMachine.getGuest().ipAddress);
		//endpointSsh.connect();

	
		// install agent
//
//	endpointSsh
//				.copyFile(
//					"C:\\Users\\user\\Desktop\\ctagent\\CounterTack Agent Installer Hiding.exe",
//						"CounterTack Agent Installer Hiding.exe");
//
//	endpointSsh
//				.runCommand("cmd /c \"C:\\Users\\user\\CounterTack Agent Installer Hiding.exe\" /S /HOST:10.150.100.235 /PORT:443");
//
//		System.out.println("Installing agent on endpoint");
//		Thread.sleep(120000);
		
		String eId = null;
		ResultSet endpointIdRes = iConnector
				.executeQueryAndReturnResults("select id from endpoints where ip='"
						+ endPointMachine.getGuest().ipAddress
						+ "'"
						+ " and status='ON' order by time_started desc limit 1");
		
		
		
		

		while (endpointIdRes.next()) {
			try{
				eId = endpointIdRes.getString(1);
			}catch(Exception e){
				
				
			}
			

			System.out.println("endpoint Id>>>>>>" + eId);

		}

		if (eId == null) {

			System.out.println("endpoint is not installed");

			System.exit(0);

		}
	
		pauseEndpoint(eId);
		Thread.sleep(60000);
		endpointSsh.closeSession();
		endpointSsh.doReconnect=false;
		// retriving endpoint id

	

		// applying profile to endpoint

		String payload = "{ " + "  \"type\": \"apply_profile_to_endpoints\", "
				+ "  \"profile\":\"Ramana-Profile-AnyInbound\", "
				+ "  \"endpoints\":[ " + "\"" + eId + "\" " + "] " + "} ";
		System.out.println("payload>>>" + payload);
		//
		


	
	
	HttpClientUtils.composePostRequest(
			"https://10.150.100.243:9090/api/v1/endpoints/command", payload);
	
	Thread.sleep(3000);
		// resume endpoint

		resumeEndpoint(eId);
		
		
		Thread.sleep(30000);
		
		
		
		
		
		
		
new Thread(new Runnable() {
	
	@Override
	public void run() {
			        	String command [] = {"ftp ", "10.140.63.156"};
			       StringBuffer output = new StringBuffer();
			        try{
		             Process p = Runtime.getRuntime().exec(command);
	           InputStreamReader ir = new InputStreamReader (p.getInputStream());
		            int outputChar = 0;
			            while((outputChar = ir.read()) != -1){
			                output.append((char)outputChar);
			            if(!ir.ready()){ // If the next read is not guaranteed, come out of loop.
		                break;
			            }
			                }
			            ir.close();
			            System.out.println("FTP is connected");
			           
			        }catch (IOException e){
			           e.printStackTrace();
				        }
				       System.out.println("ftp output >>>>>"+output.toString()); 
				        
	        }
		
	
}).start();

Thread.sleep(6000);




		
ResultSet brs = iConnector
.executeQueryAndReturnResults("select hex(id) from behaviors where uri like '%"
		+ eId + "%'  order by event_start_time desc limit 1");
String bhid = null;

while (brs.next()) {
bhid = brs.getString(1);

}
System.out.println("behavior id>>>>" + bhid);

// verifying netcat client
ResultSet netcatpros = iConnector
.executeQueryAndReturnResults("select target_thread_process_name from behaviors_denorm where hex(behavior_id)='"
		+ bhid + "' and behavior_id is not null and is_origin=1");

while (netcatpros.next()) {
String path = netcatpros.getString(1);

if (path != null) {

System.out.println("path>>>" + path);
if (path.contains("File")) {

	System.out.println("testcase passed");
	
	System.exit(0);
	return;

}

}
}
System.out.println("testcase failed");
System.exit(0);
		

		
		
		
		
		
		
		
	}
	
	
	public static void main_test(String[] args) throws Exception{
		
		
	 	String command [] = {"ftp ", "10.140.63.156"};
	       StringBuffer output = new StringBuffer();
	        try{
          Process p = Runtime.getRuntime().exec(command);
    InputStreamReader ir = new InputStreamReader (p.getInputStream());
         int outputChar = 0;
	            while((outputChar = ir.read()) != -1){
	                output.append((char)outputChar);
	            if(!ir.ready()){ // If the next read is not guaranteed, come out of loop.
             break;
	            }
	                }
	            ir.close();
	            System.out.println("FTP is connected");
	           
	        }catch (IOException e){
	           e.printStackTrace();
		        }
		       System.out.println("ftp output >>>>>"+output.toString()); 
		
		
	}

}
